package com.jy.controller;

import com.jy.common.*;
import com.jy.model.Department;
import com.jy.model.User;
import com.jy.service.UserInfoService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by Administrator on 2017/5/10 0010.
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    MultipartResolver multipartResolver;
    @RequestMapping("/dologin")
    public @ResponseBody  Map<String, Object> dologin(User user, HttpSession session){
        String users=null;
        Map<String, Object> map = new HashMap<String, Object>();
        String csrf = CSRFTokenManager.getTokenForSession(session);
        if (csrf == null || !csrf.equals(session.getAttribute(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME).toString())) {
            return map;
        } else {
        try {

                users = userInfoService.getUser(user, session);
                // System.out.println(CSRFTokenManager.getTokenForSession(session));

                map.put("users", users);
                map.put("csrf", csrf);
            } catch(ServiceException e){
                users = null;
            }
            return map;
        }
    }
    @RequestMapping("/reg")
    public @ResponseBody String reg(HttpServletRequest request,User user) throws IOException {
        user=toimages(user);

        String code=mailcode.encode2hex(user.getMailbox());
        user.setCode(code);
        //发送激活邮件
        SendEmail.send(user.getMailbox(),user.getCode(),"Validate");
        String uuid=userInfoService.saveUser(user);
        JSONObject jsonObject=new JSONObject();
        jsonObject.accumulate("uuid",uuid);
        jsonObject.accumulate("username",user.getUsername());
        return jsonObject.toString();
    }

    /**
     * 获取部门Select2
     * @param dept
     * @param flag
     * @return
     * @throws IOException
     */
    @RequestMapping("/getDepartment")
    public @ResponseBody String getDepartment(String dept,String flag,String fatherId) throws IOException {
        List<Department>list=userInfoService.getDepartment(dept,flag,fatherId);
        JSONObject jb=null;
        JSONArray jsons=new JSONArray();
        for(Department d:list){
            jb=new JSONObject();
            jb.put("id", d.getDepartment_id());
            jb.put("name",d.getDepartment_name());
            jsons.add(jb);
        }
        return jsons.toString();
    }
    public User toimages(User user){
        String imgs=user.getImgs();
        String imgs2=user.getImgs2();
        String imgs3=user.getImgs3();
        if(!"".equals(imgs)&&imgs!=null){
            imgs=user.getImgs().substring(user.getImgs().indexOf(",")+1);
        }
        if(!"".equals(imgs2)&&imgs2!=null){
            imgs2=user.getImgs2().substring(user.getImgs2().indexOf(",")+1);
        }
        String filepath;
        if(!"".equals(imgs3)&&imgs3!=null){
            imgs3=user.getImgs3().substring(user.getImgs3().indexOf(",")+1);
             filepath=Base64Image.GenerateImage(imgs,createPath(user.getImgsname()))+
                    ";"+Base64Image.GenerateImage(imgs2,createPath(user.getImgsname2()))+
                    ";"+Base64Image.GenerateImage(imgs3,createPath(user.getImgsname3()));
        }else{
             filepath=Base64Image.GenerateImage(imgs,createPath(user.getImgsname()))+
                    ";"+Base64Image.GenerateImage(imgs2,createPath(user.getImgsname2()));
        }
        user.setCard_information(filepath);
        return user;
    }
    public  String createPath(String imagName){
        Properties prop =  new  Properties();
        InputStream ins =LoginController.class.getResourceAsStream("/filepath.properties");
        try {
            prop.load(ins);
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        String savePath=prop.getProperty("filepath");
        File filefolder=new File(savePath);
        if(!filefolder.isDirectory()){
            filefolder.mkdirs();
        }
        String a=imagName.substring(0, imagName.indexOf("."));
        String b=imagName.substring(imagName.indexOf("."));
        long seconds=System.currentTimeMillis();
        String path=savePath+"/"+a+"-"+seconds+b;
        return path;
    }

    @RequestMapping("/Validate")
    public String Validate(String code, String mail, ModelMap map) throws IOException {
        try{
            userInfoService.processActivate(code,mail);
        }catch (ServiceException e){
            map.put("message",e.getMessage());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "codemail";
    }

    @RequestMapping("/sendmail")
    public @ResponseBody boolean sendmail(String mail) throws IOException {
        userInfoService.sendupdate(mail);
        return true;
    }
    @RequestMapping("/toModifyPwd")
    public  String toModifyPwd(String mail,String code,ModelMap map) throws IOException {
        map.put("mail",mail);
        map.put("code",code);
        return "modifyPwd";
    }
    @RequestMapping("/modifyPwd")
    public @ResponseBody String modifyPwd(String mail,String code,ModelMap map,String password) throws IOException {
        JSONObject json=new JSONObject();
        try {
            System.out.println(mail+"=========="+code+"========"+password);
            userInfoService.modifyPwd(mail,code,password);
        }catch (ServiceException e){
            json.put("message",e.getMessage());
        }
        return json.toString();
    }
    @RequestMapping("/getUserInfo")
    public @ResponseBody User getUserInfo(String id){
        return userInfoService.getUserInfo(id);
    }
    @RequestMapping("/validateReg")
    public @ResponseBody String validateReg(User user){
        JSONObject json=new JSONObject();
        try {
            userInfoService.validateReg(user);
            json.put("message",true);
        } catch (ServiceException e) {
            json.put("message",e.getMessage());
        }
        return json.toString();
    }

    @RequestMapping("/getSession")
    public  @ResponseBody String sessionHandlerByCacheMap(HttpSession session)
    {
        // TODO Auto-generated method stub
        User uy=(User) session.getAttribute(SessionInfo.SessionName);
        HttpSession userSession=null;
        String msg="";
        if(uy!=null){


        String userid=uy.getId();

        System.out.println(SessionListener.sessionContext.getSessionMap().get(userid));
        if(SessionListener.sessionContext.getSessionMap().get(userid)!=null){
            //userSession =(HttpSession)SessionListener.sessionContext.getSessionMap().get(userid);
            userSession =(HttpSession)SessionListener.sessionContext.getSessionMap().get(session.getId());
            //注销在线用户
            System.out.println("userSession"+userSession);
            if(userSession==null){
                msg="您的账号已经在另一处登录，您被迫下线！";
            }
            /*if(userSession!=null&&!userSession.getId().equals(session.getId())){
             //   SessionListener.sessionContext.getSessionMap().remove(userid);
                System.out.println("session.getId():"+session.getId());
                SessionListener.sessionContext.getSessionMap().remove(session.getId());
                msg="您的账号已经在另一处登录，您被迫下线！";
                // userSession.invalidate();
            }*/
            /*SessionListener.sessionContext.getSessionMap().remove(userid);
            //清除在线用户后，更新map,替换map sessionid
            SessionListener.sessionContext.getSessionMap().remove(session.getId());
            SessionListener.sessionContext.getSessionMap().put(userid,session);//用户和session
            if (session != null) {
                SessionListener.sessionContext.getSessionMap().put(session.getId(), session);//sessionid和session
            }*/
        }
        }
        /*else
        {
            // 根据当前sessionid 取session对象。 更新map key=用户名 value=session对象 删除map
            SessionListener.sessionContext.getSessionMap().get(session.getId());
            SessionListener.sessionContext.getSessionMap().put(userid,SessionListener.sessionContext.getSessionMap().get(session.getId()));
            SessionListener.sessionContext.getSessionMap().remove(session.getId());
        }*/
        return msg;
    }

    /*@RequestMapping("/getSession")
    public @ResponseBody HttpSession sessionHandlerByCacheMap(HttpSession session)
    {
        // TODO Auto-generated method stub
        User uy=(User) session.getAttribute(SessionInfo.SessionName);
        String userid=uy.getId();
        System.out.println(SessionListener.sessionContext.getSessionMap().get(userid));
        HttpSession userSession=null;
        if(SessionListener.sessionContext.getSessionMap().get(userid)!=null){
            userSession=(HttpSession)SessionListener.sessionContext.getSessionMap().get(userid);
            //注销在线用户
            System.out.println(SessionListener.sessionContext.getSessionMap().get(userid));

            if(userSession!=null&&!userSession.getId().equals(session.getId())){
                userSession.invalidate();
            }
            SessionListener.sessionContext.getSessionMap().remove(userid);
            //清除在线用户后，更新map,替换map sessionid
            SessionListener.sessionContext.getSessionMap().remove(session.getId());
            SessionListener.sessionContext.getSessionMap().put(userid,session);
            if (session != null) {
                SessionListener.sessionContext.getSessionMap().put(session.getId(), session);
            }
        }
        else
        {
            // 根据当前sessionid 取session对象。 更新map key=用户名 value=session对象 删除map
            SessionListener.sessionContext.getSessionMap().get(session.getId());
            SessionListener.sessionContext.getSessionMap().put(userid,SessionListener.sessionContext.getSessionMap().get(session.getId()));
            SessionListener.sessionContext.getSessionMap().remove(session.getId());
        }
        return  userSession;
    }*/
}
